package com.farm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.farm.entity.Cart;
import com.farm.entity.Order;
import com.farm.entity.Product;
import com.farm.entity.User;
import com.farm.service.CartService;
import com.farm.service.OrderService;
import com.farm.service.ProductService;
import com.farm.service.UserService;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        User currentUser = userService.getCurrentUser();
        model.addAttribute("user", currentUser);
        return "employee/dashboard";
    }

    // 商品浏览
    @GetMapping("/products")
    public String productList(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer size,
                            @RequestParam(required = false) String category,
                            Model model) {
        IPage<Product> products = productService.getProductList(page, size, category);
        model.addAttribute("products", products);
        model.addAttribute("category", category);
        return "employee/product/list";
    }

    @GetMapping("/products/{id}")
    public String productDetail(@PathVariable Long id, Model model) {
        Product product = productService.getProductById(id);
        model.addAttribute("product", product);
        return "employee/product/detail";
    }

    // 购物车管理
    @GetMapping("/cart")
    public String cart(Model model) {
        User currentUser = userService.getCurrentUser();
        List<Cart> cartItems = cartService.getUserCart(currentUser.getId());
        model.addAttribute("cartItems", cartItems);
        return "employee/cart";
    }

    @PostMapping("/cart/add")
    @ResponseBody
    public String addToCart(@RequestParam Long productId, @RequestParam Integer quantity) {
        try {
            User currentUser = userService.getCurrentUser();
            cartService.addToCart(currentUser.getId(), productId, quantity);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/cart/{cartId}/update")
    @ResponseBody
    public String updateCartQuantity(@PathVariable Long cartId, @RequestParam Integer quantity) {
        try {
            cartService.updateQuantity(cartId, quantity);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/cart/{cartId}/remove")
    @ResponseBody
    public String removeFromCart(@PathVariable Long cartId) {
        try {
            cartService.removeFromCart(cartId);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    // 订单管理
    @PostMapping("/orders/create")
    public String createOrder(RedirectAttributes redirectAttributes) {
        try {
            User currentUser = userService.getCurrentUser();
            Order order = orderService.createOrder(currentUser.getId());
            redirectAttributes.addFlashAttribute("message", "订单创建成功");
            return "redirect:/employee/orders/" + order.getId();
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "创建订单失败：" + e.getMessage());
            return "redirect:/employee/cart";
        }
    }

    @GetMapping("/orders")
    public String orderList(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer size,
                          Model model) {
        User currentUser = userService.getCurrentUser();
        IPage<Order> orders = orderService.getUserOrders(currentUser.getId(), page, size);
        model.addAttribute("orders", orders);
        return "employee/order/list";
    }

    @GetMapping("/orders/{id}")
    public String orderDetail(@PathVariable Long id, Model model) {
        Order order = orderService.getOrderById(id);
        model.addAttribute("order", order);
        return "employee/order/detail";
    }

    @PostMapping("/orders/{orderId}/cancel")
    @ResponseBody
    public String cancelOrder(@PathVariable Long orderId) {
        try {
            orderService.cancelOrder(orderId);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/orders/{orderId}/confirm")
    @ResponseBody
    public String confirmReceipt(@PathVariable Long orderId) {
        try {
            orderService.confirmReceipt(orderId);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }
} 